﻿using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using LoginServer.Models;
using Microsoft.AspNetCore.Mvc;

namespace LoginServer.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class LoginController : ControllerBase
    {
        [HttpPost(nameof(RequestToken))]
        public async Task<ActionResult> RequestToken(LoginRequest loginRequest)
        {
            Dictionary<string, string> dict = new Dictionary<string, string>();
            dict["client_id"] = "HYD-PC-101";
            dict["client_secret"] = "HYD-PC-101:123654";
            dict["grant_type"] = "password";

            dict["username"] = loginRequest.UserName;
            dict["password"] = loginRequest.Password;

            Console.WriteLine($"用户名：{loginRequest.UserName}，密码:{loginRequest.Password}");

            //由登录服务器向IdentityServer发请求获取Token
            using (HttpClient http = new HttpClient())
            {
                using (var content = new FormUrlEncodedContent(dict))
                {
                    var msg = await http.PostAsync("http://127.0.0.1:50101/connect/token", content);

                    string result = await msg.Content.ReadAsStringAsync();

                    return Content(result, "application/json");
                }
            }
        }
    }
}